<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="等级名称" prop="levelName">
        <el-input
          v-model="queryParams.levelName"
          placeholder="请输入等级名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="会员时长" prop="duration">
        <el-input
          v-model="queryParams.duration"
          placeholder="请输入会员时长"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="会员价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入会员价格"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="权益说明" prop="vipRights">
        <el-input
          v-model="queryParams.vipRights"
          placeholder="请输入会员权益说明"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择会员启用状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.TRAIN_VIP_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['train:vip-level:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['train:vip-level:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['train:vip-level:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="序号">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="等级名称" align="center" prop="levelName">
        <template #default="scope">
          <el-tag type="primary">{{scope.row.levelName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="会员时长" align="center" prop="duration" />
      <el-table-column label="会员价格" align="center" prop="price" />
      <el-table-column label="会员权益说明" align="center" prop="vipRights" />
      <el-table-column label="会员启用状态" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['train:vip-level:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['train:vip-level:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <VipLevelForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { VipLevelApi, VipLevel } from '@/api/train/viplevel'
import VipLevelForm from './VipLevelForm.vue'

// Removed `const { proxy } = getCurrentInstance()` as it's not strictly needed for the fix,
// and you're already using `useMessage()`. If `proxy` is used elsewhere for other global properties,
// you might keep it, but for $modal/confirm it's not the idiomatic way in Composition API.

/** 会员等级设定 列表 */
defineOptions({ name: 'VipLevel' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<VipLevel[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  levelName: undefined,
  duration: undefined,
  price: undefined,
  vipRights: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await VipLevelApi.getVipLevelPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm() // Using message.delConfirm
    // 发起删除
    await VipLevelApi.deleteVipLevel(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除会员等级设定 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm() // Using message.delConfirm
    await VipLevelApi.deleteVipLevelList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: VipLevel[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm() // Using message.exportConfirm
    // 发起导出
    exportLoading.value = true
    const data = await VipLevelApi.exportVipLevel(queryParams)
    download.excel(data, '会员等级设定.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}


const formData = ref({
  id: undefined,
  status: undefined
})
/** 状态修改  */
function handleStatusChange(row: VipLevel) { // Added type for `row` for better type safety
  let text = row.status === 0 ? "停用" : "启用";
  // Changed proxy.$modal.confirm to message.confirm
  message.confirm('确认要"' + text + '"吗?').then(async function () { // Added async here for await
    formData.value.id = row.id;
    formData.value.status = row.status;
    const data = formData.value as unknown as VipLevel
    await VipLevelApi.updateVipLevel(data) // Await the API call
    // Changed proxy.$modal.msgSuccess to message.success
    message.success(text + "成功");
  }).catch(function () {
    // If the user cancels or an error occurs, revert the switch state
    row.status = row.status === 0 ? 1 : 0;
  });
};
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
